/**
 * @file 系统状态监听器 Composable
 * @description 统一管理系统状态变化的监听，包括主题、语言、快捷键等
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-07-10
 */

import { onBeforeUnmount, watch, type WatchStopHandle } from 'vue'
import { useLocale, useTheme } from 'vuetify'
import '@/utils/esc-manager'
import { systemState } from 'global-state'

/**
 * 系统状态监听器 Composable
 * @description 提供系统状态变化的监听功能，包括主题、语言、快捷键等
 * @returns 监听器控制函数
 */
export function useSystemStateListener() {
  console.log('🎧 启动系统状态监听器')

  // 获取各种状态和工具
  const theme = useTheme()
  const { current } = useLocale()

  // 存储所有监听器的停止函数
  const stopHandles: WatchStopHandle[] = []

  // 监听用户主题设置变化
  const userThemeWatcher = watch(
    () => systemState.state.theme,
    newTheme => {
      theme.change(newTheme)
    },
    { immediate: true }
  )

  stopHandles.push(userThemeWatcher)

  // 设置语言监听器
  const languageWatcher = watch(
    () => systemState.state.language,
    newLanguage => {
      console.log('语言已切换至:', newLanguage)
      current.value = newLanguage
      console.log('当前语言设置:', current.value)
    },
    { immediate: true }
  )

  stopHandles.push(languageWatcher)

  // 清理函数
  const cleanup = () => {
    console.log('🔇 清理系统状态监听器')
    for (const stop of stopHandles) stop()
  }
  // 在组件卸载时自动清理所有监听器
  onBeforeUnmount(cleanup)
}
